import axios from 'axios'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers.token = window.sessionStorage.getItem('token')
    // 必须return config
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

//axios拦截器 (添加响应拦截器)
service.interceptors.response.use(function(response) {
    let res = response.data;
    if (res.code === 'EXP1000') {
      window.sessionStorage.removeItem('token')// 删除已经失效或过期的token（不删除也可以，因为登录后覆盖）
      router.replace({
        path: `/login?redirect=${this.$route.fullPath}` // 到登录页重新获取token
      })
    }
    return res
  },function (error) {
    this.$message.error(res.msg)
    return Promise.reject(error)
  }
)
export default service
